<?php

namespace app\api;

use app\model\Player;
use plugin\admin\app\common\Util;
use Respect\Validation\Validator as v;
use support\Db;
use support\Request;
use support\Response;
use function Respect\Stringifier\stringify;

class Login
{
    public function login(Request $request)
    {
        $data = $request->all();
        if(Player::query()->where('username', $data['username'])->where('password', Util::passwordMd5($data['password']))->exists()) {
            try {
                session()->set('login_user', $data['username']);
            } catch (\Exception $e) {
                return jsonFail(100,$e);
            }
            return json(['code'=>0, 'msg'=>'登陆成功']);
        } else {
            return json(['code'=>1, 'msg'=>'用户名或密码错误']);
        }
    }

    public function register(Request $request)
    {
        $data = v::input($request->post(), [
            'username' => v::length(4, 16)->setName('用户名'),
            'password' => v::length(6, 20)->setName('密码'),
            'phone' => v::notEmpty()->length(11,11)->regex('/^1[345789][0-9]{9}$/')->setName('手机号码'),   //todo;设置手机格式错误提示
            'email' => v::notEmpty()->length(6, 30)->regex('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/')->setName('邮箱'),    //todo;设置邮箱格式提示
        ]);

        if(Player::query()->where('username', $data['username'])->where('password', Util::passwordMd5($data['password']))->exists()) {
            return json(['code'=>1, 'msg'=>'该账户已经存在！']);
        } else {
            try {
                session()->set('login_user', $data['username']);
            } catch (\Exception $e) {
                return jsonFail(100,$e);
            }
            DB::beginTransaction();
            try {
                $user = new Player();
                $user->username = $data['username'];
                $user->password = Util::passwordMd5($data['password']);
                $user->phone = $data['phone'];
                $user->email = $data['email'];
                $user->sex = $data['sex'] ?? 0;
                $user->uid = substr($data['phone'], -8);
                $user->money = 100; //初始金额设置为100
                $user->score = 100; //初始积分设置为100
                $user->save();
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return jsonFail(100, '注册失败');
            }
            return json(['code'=>0, 'msg'=>'注册成功！']);
        }
    }
}